package tgc.edu.exam.service;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import tgc.edu.exam.custom.CommonService;
import tgc.edu.exam.entity.TbMenu;
import tgc.edu.exam.repository.MenuReopsitory;
import tgc.edu.exam.security.UserUtils;
@Service
public class MenuService extends CommonService<TbMenu, UUID>{
	@Autowired
	private MenuReopsitory menuReopsitory;
	@Autowired
	private UserUtils userUtils;
	public List<TbMenu> findByParentIsNull() {
		return menuReopsitory.findByParentIsNull();
		
	}
	
	/***
	 * 取出用户有权限的菜单项
	 *
	 * @return 用户要显示的菜单项
	 */

	public List<TbMenu> findAuditMenu() {
		List<TbMenu> menus;
		if(userUtils.hasRole("ROLE_DIY")) {
			menus=menuReopsitory.findByParentIsNull();
		}else {
			menus=auditMenu(menuReopsitory.findByParentIsNull());
		}
		return menus;
	}
	
	private List<TbMenu> auditMenu(List<TbMenu> menus) {
		List<TbMenu> list=new ArrayList<>();
		for (TbMenu menu : menus) {
			String code = menu.getRole().getCode();
			if(userUtils.hasRole(code)) {
				list.add(menu);
				if(menu.getChildren()!=null&&!menu.getChildren().isEmpty()) {
					menu.setChildren(auditMenu(menu.getChildren()));
				}
			}
		}
		return list;
	}

	
}
